/*
 * Copyright (c) 2023 OceanBase.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.oceanbase.tools.sqlparser.statement.select;

import java.util.List;
import java.util.stream.Collectors;

import org.antlr.v4.runtime.ParserRuleContext;

import com.oceanbase.tools.sqlparser.statement.BaseStatement;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;

/**
 * {@link OrderBy}
 *
 * @author yh263208
 * @date 2022-12-06 11:59
 * @since ODC_release_4.1.0
 * @see BaseStatement
 */
@Getter
@EqualsAndHashCode(callSuper = false)
public class OrderBy extends BaseStatement {

    private final boolean siblings;
    private final List<SortKey> sortKeys;

    public OrderBy(@NonNull ParserRuleContext context,
            boolean siblings, @NonNull List<SortKey> sortKeys) {
        super(context);
        this.siblings = siblings;
        this.sortKeys = sortKeys;
    }

    public OrderBy(@NonNull ParserRuleContext context,
            @NonNull List<SortKey> sortKeys) {
        super(context);
        this.siblings = false;
        this.sortKeys = sortKeys;
    }

    public OrderBy(@NonNull List<SortKey> sortKeys) {
        this.siblings = false;
        this.sortKeys = sortKeys;
    }

    public OrderBy(boolean siblings, @NonNull List<SortKey> sortKeys) {
        this.siblings = siblings;
        this.sortKeys = sortKeys;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder("ORDER");
        if (this.siblings) {
            builder.append(" ").append("SIBLINGS");
        }
        builder.append(" BY ")
                .append(this.sortKeys.stream()
                        .map(SortKey::toString).collect(Collectors.joining(",")));
        return builder.toString();
    }

}
